<!-- 考试等级饼图 -->
<template>
  
  <div class="chart-container">
    <!-- 饼图 -->
    <div class="chart-pie" ref="pieChart"></div>
  </div>
</template>

<script setup>
import * as echarts from "echarts";
import axios from "axios";
// import UserStatisticsApi from "src\api\Backend\userStatisticsApi";

onUnmounted(() => {
  if (myPieChart && myPieChart.dispose) {
    myPieChart.dispose();
  }
});
import {
  TitleComponent,
  ToolboxComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
} from "echarts/components";
import { LineChart, PieChart } from "echarts/charts";
import { UniversalTransition, LabelLayout } from "echarts/features";
import { CanvasRenderer } from "echarts/renderers";
import { pa } from "element-plus/es/locales.mjs";
import UserStatisticsApi from "@/api/Backend/userStatisticsApi";

echarts.use([
  TitleComponent,
  ToolboxComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  LineChart,
  CanvasRenderer,
  UniversalTransition,
  PieChart,
  CanvasRenderer,
  LabelLayout,
]);

// 创建一个响应式引用来保存 DOM 元素
const pieChart = ref(null);
let myPieChart = null;

// 初始化 ECharts 实例并设置配置项
onMounted(async () => {
  // 确保 DOM 已经渲染完成
  await nextTick();
  //初始化 ECharts 引入echarts
  myPieChart = echarts.init(pieChart.value);
  // 设置饼图 图表
try{
  // 4. 调用后端接口（需和 Spring Boot 接口地址匹配，可配置代理解决跨域）
  // const res = await axios.get("/api/userStatistics/scoreLevel",{params:{contestId: null}}); 
  const res = await UserStatisticsApi.getScoreLevel();
  console.log(res,'111');
  const reultdata =res.data;
  
  const optionPie = {
     // 添加标题配置
  title: {
    text: '考试等级总览',
    left: '2%',      // 标题水平居中
    top: '3%',           // 标题距离顶部的位置
    textStyle: {
      fontSize: 18,      // 标题字体大小
      fontWeight: 'bold' // 标题字体加粗
    }
  },
    tooltip: {
      trigger: "item",
      // formatter: "{b}: {c} ({d}%)" // 显示百分比
    },
    legend: {
      top: "15%",
      // bottom: "15%",
      
      left: "center",
    },
    series: [
      {
        name: "成绩等级",
        type: "pie",
        radius: ["40%", "70%"],
        avoidLabelOverlap: false,
        label: {
          show: true,
          position: 'outside',
           formatter: "{b}: {d}%", // 显示名称和百分比
          //  distanceToLabelLine: 1,
           labelLayout: (params) => ({ rotate: params.angle / Math.PI * 180 }), // 可选优化
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 15,
            fontWeight: "bold",
          },
        },
        labelLine: {
          // show: true,
          length: -35,
          length2: 2,
        },
        data: reultdata,
      },
    ],
  };
  optionPie && myPieChart.setOption(optionPie);
} catch (error) {
  console.error("Error initializing ECharts:", error);
}
  
});
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 400px;
  display: flex;
}

.chart-pie {
  width: 100%;
  height: 100%;
}
</style>
